#!/bin/bash
#ip格式
#192.168.0.1:113
user=root
catalog=/root/.ssh
[ ! -f $catalog ] && mkdir -p $catalog && ssh-keygen -P '' -f $catalog/id_rsa
#判断是否安装expect
expect -version
[ $? -ne 0 ] && yum install -y expect && echo "expect安装成功" #centos用
#[ $? -ne 0 ] && apt -y install expect && echo "expect安装成功"  #ubuntu用
for i in `cat ip`
do
        ip=`echo $i|cut -d: -f1`
        passwd=`echo  $i|cut -d: -f2`
        ping -c1 $ip &>/dev/null
        if [ $? -eq 0 ];then
        echo $ip >> ~/ip_up.txt
/usr/bin/expect <<-END
                set timeout 10
                spawn ssh-copy-id $user@$ip
        expect "yes/no"  {send "yes\r";exp_continue }
        expect "password:" { send  "$passwd\r" }
        spawn ssh $user@$ip
        expect "yes/no"  {send "yes\r";exp_continue }
        expect "password:" { send  "$passwd\r" }        
        expect ":~#" {send "chmod 600 /root/.ssh/authorized_keys\r"}
        expect ":~#" {send "sed -i '5aAuthorizedKeysFile  .ssh/authorized_keys .ssh/authorized_keys2' /etc/ssh/sshd_config\r"}
        expect ":~#" {send "sed -i '5aPubkeyAuthentication yes' /etc/ssh/sshd_config\r"}
        expect ":~#" {send "sed -i '5aPasswordAuthentication no' /etc/ssh/sshd_config\r"}
        expect ":~#" {send "systemctl restart ssh\r"}
        expect eof
END
        else
                echo $ip >>ip_down.txt
        fi
done
succeed=`cat ip_up.txt|wc -l`
echo "$succeed公钥推送成功"
error=`cat ip_down.txt|wc -l`
echo "$error个推送不成功，请查看ip_down.txt"
echo "alias s='ssh -l root -p 22 -o StrictHostKeyChecking=no'" >>/root/.bashrc
source /root/.bashrc
 
